<?php


namespace App\Kuafu\Customer\Controller\Applet;

use App\Kuafu\Common\Service\CommonService;
use App\Kuafu\Customer\Enum\CustomerCodeEnum;
use App\Kuafu\Customer\Enum\PlatformCodeEnum;
use App\Kuafu\Customer\Model\CustomerActionLogModel;
use App\Kuafu\Customer\Model\CustomerPlatformModel;
use App\Kuafu\Customer\Service\CustomerActionLogService;
use App\Kuafu\Customer\Service\CustomerPlatformService;
use App\Kuafu\Customer\Service\CustomerService;
use App\Kuafu\Customer\Validate\LoginValidate;
use App\Kuafu\Shop\Service\DouyinSelfLibrary\DouyinSelfService;
use App\Kuafu\Wechat\Service\WechatService;
use App\Support\AppletEncrypt;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Kuafu\Base\Controller\BaseController;

class LoginController extends BaseController
{
    /**
     * 用户登录
     * @param Request $request
     * @return JsonResponse
     */
    public function registerOrLogin(Request $request): JsonResponse
    {
        $appid      = (string)$request->header('appId');
        $platformId = (int)$request->header('platformId',1);
        $valid      = LoginValidate::loginCheck($request->code, $platformId);
        if ($valid) {
            return $this->fail(CustomerCodeEnum::ERR_400000, $valid);
        }
        $type = CustomerActionLogModel::ACTION_TYPE_APPLET_REGISTER;// 小程序用户注册
        switch ($platformId){
            case PlatformCodeEnum::PLATFORM_APPLET_DOUYIN:// 抖音小程序
                $result = DouyinSelfService::AuthCodeToSession($request->code, $appid);
                break;
            case PlatformCodeEnum::PLATFORM_WECHAT_SERVICE:// 微信服务号
                $result = WechatService::AuthCodeToAccessToken($request->code, $appid, $platformId);
                $type   = CustomerActionLogModel::ACTION_TYPE_WECHAT_SERVICE_REGISTER;// 微信服务号用户注册
                break;
            default:
                $result = WechatService::AuthCodeToSession($request->code, $appid);
        }
        //通过用户unionid查询用户都否存在
        $byUnionid = CustomerPlatformService::getUserInfoByUnionid($result['unionid'], $platformId,
            ['id', 'userId', 'openId']);
        //保存sessionKey
        if (isset($result['session_key'])) {
            Redis::setex('SESSION_KEY_UNIONID:' . $result['unionid'], 259000, $result['session_key']);
        }
        if (empty($byUnionid)) {
            $data      = [
                'name'       => $result['nickname'] ?? '',
                'platformId' => $platformId,
                'openid'     => $result['openid'],
                'unionid'    => $result['unionid'],
                'headImage'  => $result['headimgurl'] ?? '',
            ];
            $byUnionid = CustomerPlatformService::addCustomerPlatMapping($data);
            // 异步添加用户日志
            (new CustomerActionLogService())->asynSaveData([
                'userId'   => 0,
                'unionId'  => $result['unionid'],
                'type'     => $type,
                'userInfo' => [
                    'shopId' => $this->shopId,
                    'openId' => $result['openid'],
                ]
            ]);

        } else {
            DB::beginTransaction();
            try {
                if ($result['openid'] != $byUnionid['openId']) {
                    CustomerPlatformService::setOpenIdByUnionId($result['unionid'], $platformId, $result['openid']);
                }
                if ($byUnionid['userId']) {
                    $info = CustomerService::getUserInfo(['id' => $byUnionid['userId']], ['loginTimes']);
                    //记录最新登录ip以及添加次数
                    $setData = [
                        'loginTimes'    => $info['loginTimes'] + 1,
                        'lastLoginAt'   => time(),
                        'lastLoginIpAt' => (int)ip2long(CommonService::getRealIp())
                    ];
                    CustomerService::setCustomer($byUnionid['userId'], $setData);
//                    try {
//                        //匿名绑定
//                        SensorsDataJob::dispatch(
//                            $this->shopId,
//                            $byUnionid['userId'],
//                            SensorsDataJob::TYPE_USER_BIND,
//                            [
//                                'uid'    => (int)$byUnionid['userId'],
//                                'openid' => $result['openid']
//                            ]
//                        )->onQueue(SensorsDataJob::$QUEUE_NAME);
//                    } catch (\Exception $e) {
//                        CommonService::fsLogException('[ 神策埋点 ] - [ 匿名绑定 ] - [ 生产队列失败 ]', $e,
//                            ['uid' => $byUnionid['userId'], 'openid' => $result['openid']]);
//                    }
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return $this->fail(CustomerCodeEnum::ERR_LOGIN, $e->getMessage());
            }
        }
        //生成token返回
        $token = AppletEncrypt::getInstance()->encryptData($result['unionid'], $platformId);
        return $this->success(['token' => $token, 'userId' => $byUnionid['userId'], 'openId' => $result['openid']]);
    }
}
